package com.lab.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lab.pojo.Student;
import com.lab.service.StudentService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stu")
public class StudentController {
    @Resource
    StudentService studentService;
    private Map<String,Object> result= new HashMap<>();
    /**
     * 查询所有学生信息
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/listByPage")
    public Map<String,Object> listByPage(Integer page, Integer rows){
        //设置分页参数
        page=(page-1)*rows;
        PageHelper.offsetPage(page, rows);
        //查询所有数据
        List<Student> list=studentService.allStudents();

        //使用PageInfo封装查询结果
        PageInfo<Student> pageInfo=new PageInfo<Student>(list);
        for(Student student:list){
            if(student.getState().equals("1")){
                student.setState("正常");
            }else{
                student.setState("停用");
            }
        }
        //从PageInfo对象取出查询结果
        //总记录数
        long total=pageInfo.getTotal();
        //当前页数据列表
        List<Student> studentList=pageInfo.getList();
        result.put("total", total);
        result.put("rows", studentList);
        return result;
    }

    /**
     * 添加和修改
     * @param stu
     * @return
     */
    @RequestMapping(value="/saveStudent",method = RequestMethod.POST)
    public Map<String,Object> saveStudent(Student stu){
        try {
            studentService.saveStu(stu);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 数据回显
     * @param sid
     * @return
     */
    @RequestMapping(value="/findStuById",method = RequestMethod.GET)
    public Student findStuById(Long sid) {
        Student stu=studentService.findStuById(sid);
        return stu;
    }

    /**
     *删除数据
     * @param sid
     * @return
     */
    @RequestMapping(value="/deleteStudent",method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String,Object> deleteStudent(Long[] sid){
        try {
            studentService.deleteStudent(sid);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }
}
